#
# @lc app=leetcode.cn id=2 lang=python3
#
# [2] 两数相加
#
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

# @lc code=start
from typing import Optional

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        carry = 0
        head = ListNode()
        temp = head
        node = ListNode(0)
        while l1 is not None or l2 is not None:
            temp.next = ListNode()
            temp = temp.next
            l1 = l1 if l1 is not None else node
            l2 = l2 if l2 is not None else node
            sum = l1.val + l2.val + carry
            temp.val = sum % 10
            carry = sum // 10
            l1 = l1.next
            l2 = l2.next
        if carry == 1:
            temp.next = ListNode(carry)

        return head.next
# @lc code=end

